<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useContainerStore } from '../stores/containerStore'
import { Search, Filter, Calendar, Star } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { API_BASE_URL } from '../utils/storage'
import { searchContainers as searchContainersAPI } from '../api/container'

// 获取认证token（如果需要）
function getAuthToken() {
  return localStorage.getItem('auth_token') || ''
}

const containerStore = useContainerStore()

// AI：搜索结果容器（由API返回）
const searchResultContainers = ref([])

// 搜索和筛选条件
const searchForm = ref({
  keyword: '',
  category: '',
  status: '',
  dateRange: [],
  minScore: 0,
  maxScore: 5
})

// 分类选项
const categoryOptions = [
  { label: '全部', value: '' },
  { label: '工作', value: '工作' },
  { label: '学习', value: '学习' },
  { label: '阅读', value: '阅读' },
  { label: '写作', value: '写作' },
  { label: '思考', value: '思考' },
  { label: '运动', value: '运动' },
  { label: '其他', value: '其他' }
]

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '进行中', value: 'active' },
  { label: '已完成', value: 'completed' }
]

// 排序选项
const sortOptions = [
  { label: '创建时间（新→旧）', value: 'startTime-desc' },
  { label: '创建时间（旧→新）', value: 'startTime-asc' },
  { label: '完成时间（新→旧）', value: 'endTime-desc' },
  { label: '完成时间（旧→新）', value: 'endTime-asc' },
  { label: '评分（高→低）', value: 'score-desc' },
  { label: '评分（低→高）', value: 'score-asc' }
]

// 当前排序方式
const currentSort = ref('startTime-desc')


// 容器搜索API调用 - 适配您提供的后端接口
async function searchContainersByAPI() {
  try {
    // 构建查询参数对象
  const query = {
      page: 1,
      // 后端参数为 size 而不是 limit
      size: 50,
      // 将前端状态映射为后端数值：active=1, completed=2
      status: (searchForm.value.status === 'active')
        ? 1
        : (searchForm.value.status === 'completed')
          ? 2
          : undefined,
      category: searchForm.value.category || undefined,
      keyword: searchForm.value.keyword || undefined,
      start_date: (searchForm.value.dateRange && searchForm.value.dateRange.length === 2)
        ? dayjs(searchForm.value.dateRange[0]).format('YYYY-MM-DD')
        : undefined,
      end_date: (searchForm.value.dateRange && searchForm.value.dateRange.length === 2)
        ? dayjs(searchForm.value.dateRange[1]).format('YYYY-MM-DD')
        : undefined,
      min_score: searchForm.value.minScore,
      max_score: searchForm.value.maxScore,
    }
    
    // 调用容器列表接口：GET /container（通过封装的 API 方法）
    const result = await searchContainersAPI(query)
    
    // 处理API响应格式 - 适配您提供的ApiResponse格式
    if (result.code === 200 && result.data) {
      // 注意：您提供的接口返回的是IPage<Container>，可能需要处理分页数据结构
      const pageData = result.data
      
      // 根据页面数据结构获取容器列表
      // 假设容器列表在pageData.records或pageData.content或直接是数组
      let containers = []
      if (Array.isArray(pageData)) {
        containers = pageData
      } else if (pageData.records && Array.isArray(pageData.records)) {
        containers = pageData.records
      } else if (pageData.content && Array.isArray(pageData.content)) {
        containers = pageData.content
      } else if (pageData.list && Array.isArray(pageData.list)) {
        containers = pageData.list
      }
      
    // 直接使用API返回的筛选结果
    searchResultContainers.value = containers
    console.log('API搜索成功，返回容器数量:', containers.length)
  } else {
    throw new Error(result.message || '搜索失败')
  }
  
} catch (error) {
  console.error('容器搜索API调用失败:', error)
  searchResultContainers.value = []
  // 可以添加用户提示
  ElMessage.error('搜索失败: ' + error.message)
}
}

// 页面挂载后自动查询一次
onMounted(() => {
  searchContainersByAPI()
})

// 可选：监听部分筛选项变化自动查询（避免频繁触发，此处只监听状态和分类）
watch(() => [searchForm.value.status, searchForm.value.category], () => {
  searchContainersByAPI()
})

// 重置搜索表单
function resetSearch() {
  searchForm.value = {
    keyword: '',
    category: '',
    status: '',
    dateRange: [],
    minScore: 0,
    maxScore: 5
  }
}

// 格式化日期
function formatDate(dateString) {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm')
}

// 获取评分颜色
function getScoreColor(score) {
  if (score >= 4) return '#67C23A' // 绿色
  if (score >= 3) return '#E6A23C' // 黄色
  return '#F56C6C' // 红色
}
</script>

<template>
  <div class="container-search-view">
    <h1>容器搜索与分类</h1>
    
    <!-- 搜索和筛选区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="100px" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="关键词搜索">
              <el-input 
                v-model="searchForm.keyword" 
                placeholder="搜索容器名称或描述"
                clearable
                :prefix-icon="Search"
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="分类">
              <el-select 
                v-model="searchForm.category" 
                placeholder="选择分类"
                clearable
                style="width: 100%"
              >
                <el-option 
                  v-for="option in categoryOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="状态">
              <el-select 
                v-model="searchForm.status" 
                placeholder="选择状态"
                clearable
                style="width: 100%"
              >
                <el-option 
                  v-for="option in statusOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="创建日期">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="评分范围">
              <div class="score-slider">
                <span class="score-label">{{ searchForm.minScore }}</span>
                <el-slider 
                  v-model="searchForm.minScore" 
                  :min="0" 
                  :max="searchForm.maxScore"
                  :step="1"
                />
              </div>
              <div class="score-slider">
                <span class="score-label">{{ searchForm.maxScore }}</span>
                <el-slider 
                  v-model="searchForm.maxScore" 
                  :min="searchForm.minScore" 
                  :max="5"
                  :step="1"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <div class="search-actions">
            <el-button @click="searchContainersByAPI" type="primary">搜索</el-button>
            <el-button @click="resetSearch" plain>重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 结果排序和展示 -->
    <div class="result-header">
      <div class="result-count">
        找到 <span class="highlight">{{ searchResultContainers.length }}</span> 个容器
      </div>
      <div class="sort-control">
        <span class="sort-label">排序方式：</span>
        <el-select v-model="currentSort" style="width: 180px">
          <el-option 
            v-for="option in sortOptions" 
            :key="option.value" 
            :label="option.label" 
            :value="option.value" 
          />
        </el-select>
      </div>
    </div>
    
    <!-- 容器列表 -->
    <div v-if="searchResultContainers.length === 0" class="no-results">
      <el-empty description="没有找到匹配的容器" />
    </div>
    <div v-else class="container-list">
      <el-card 
        v-for="container in searchResultContainers" 
        :key="container.id"
        class="container-card"
        :class="{ 'completed': container.status === 'completed' }"
      >
        <div class="container-header">
          <h3>{{ container.title }}</h3>
          <el-tag size="small">{{ container.category }}</el-tag>
        </div>
        
        <p v-if="container.description" class="container-description">
          {{ container.description }}
        </p>
        
        <div class="container-meta">
          <div class="meta-item">
            <el-icon><Calendar /></el-icon>
            <span>创建：{{ formatDate(container.startTime) }}</span>
          </div>
          
          <div v-if="container.endTime" class="meta-item">
            <el-icon><Calendar /></el-icon>
            <span>完成：{{ formatDate(container.endTime) }}</span>
          </div>
          
          <div class="meta-item">
            <span>预估时间：{{ container.estimatedTime }}分钟</span>
          </div>
          
          <div v-if="container.status === 'completed'" class="meta-item">
            <span>实际耗时：{{ container.actualTime }}分钟</span>
          </div>
        </div>
        
        <div v-if="container.status === 'completed' && container.evaluation" class="container-evaluation">
          <div class="evaluation-score">
            <el-icon><Star /></el-icon>
            <span>有效性评分：</span>
            <el-rate 
              v-model="container.evaluation.effectivenessScore" 
              disabled 
              :colors="['#F56C6C', '#E6A23C', '#67C23A']"
              :max="5"
            />
          </div>
          
          <div v-if="container.evaluation.positiveTags.length > 0" class="evaluation-tags">
            <span>正向标签：</span>
            <el-tag 
              v-for="tag in container.evaluation.positiveTags" 
              :key="tag"
              type="success"
              effect="plain"
              size="small"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
          
          <div v-if="container.evaluation.negativeTags.length > 0" class="evaluation-tags">
            <span>负向标签：</span>
            <el-tag 
              v-for="tag in container.evaluation.negativeTags" 
              :key="tag"
              type="danger"
              effect="plain"
              size="small"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
          
          <div v-if="container.evaluation.notes" class="evaluation-notes">
            <p>{{ container.evaluation.notes }}</p>
          </div>
        </div>
        
        <div v-else-if="container.status === 'active'" class="container-status">
          <el-tag type="warning">进行中</el-tag>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.container-search-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.container-search-view h1 {
  margin-bottom: 30px;
  text-align: center;
  color: var(--primary-text);
}

.search-card {
  margin-bottom: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-actions {
  display: flex;
  justify-content: flex-end;
}

.score-slider {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.score-label {
  width: 30px;
  text-align: center;
  margin-right: 10px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.result-count {
  font-size: 1rem;
  color: var(--regular-text);
}

.highlight {
  color: var(--primary-color);
  font-weight: bold;
}

.sort-control {
  display: flex;
  align-items: center;
}

.sort-label {
  margin-right: 10px;
  color: var(--regular-text);
}

.no-results {
  margin: 50px 0;
  text-align: center;
}

.container-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.container-card {
  border-radius: 8px;
  transition: all 0.3s ease;
  height: 100%;
}

.container-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.container-card.completed {
  border-left: 4px solid var(--success-color);
}

.container-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.container-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: var(--primary-text);
}

.container-description {
  color: var(--regular-text);
  margin-bottom: 15px;
  font-size: 0.9rem;
}

.container-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
  font-size: 0.9rem;
  color: var(--secondary-text);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.container-evaluation {
  border-top: 1px solid var(--border-lighter);
  padding-top: 15px;
}

.evaluation-score {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 10px;
}

.evaluation-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 5px;
  margin-bottom: 10px;
}

.tag-item {
  margin-right: 5px;
}

.evaluation-notes {
  font-size: 0.9rem;
  color: var(--regular-text);
  font-style: italic;
  background-color: var(--border-lightest);
  padding: 10px;
  border-radius: 4px;
}

.container-status {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .container-list {
    grid-template-columns: 1fr;
  }
  
  .result-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>